package ThreadPoolCheck.notify_wait.Cond2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by wangyg6 on 2017/11/9.
 */
public class UseLock {
	private boolean bShouldSub = true;
	Lock lock = new ReentrantLock();
	Condition condition = lock.newCondition();

	public void sub(int i) {
		lock.lock();
		try {
			while (!bShouldSub) {
				condition.await();
			}
			for (int j = 1; j <= 10; j++) {
				System.out.println("sub thread sequence of " + j + ",loop of " + i);
			}
			System.out.println();
			System.out.println();
			bShouldSub = false;
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			condition.signal();
			lock.unlock();
		}
	}

	public void main(int i) {
		lock.lock();
		try {
			while (bShouldSub) {
					condition.await();
			}
			for (int j = 1; j <= 10; j++) {
				System.out.println("main thread sequence of " + j + ",loop of " + i);
			}
			System.out.println();
			System.out.println();
			bShouldSub = true;
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			condition.signal();
			lock.unlock();
		}
	}
}

